package com.shop.shoporder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shop.shoporder.common.HttpRequest;
import com.shop.shoporder.common.MessageConstants;
import com.shop.shoporder.common.InterfaceVer;
import com.shop.shoporder.common.Response;
import com.shop.shoporder.entity.HttpRequestConfig;
import com.shop.shoporder.entity.order.*;
import com.shop.shoporder.mapper.order.ConfigMapper;
import com.shop.shoporder.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service("payOrderService")
public class PayOrderServiceImpl implements PayOrderService {
    @Autowired
    ConfigMapper configMapper;
    @Autowired
    FinaceService finaceService;
    @Autowired
    OrderService orderService;
    @Autowired
    CartService cartService;
    @Autowired
    UserNoService userNoService;
    @Autowired
    GroupbuyService groupbuyService;
    @Resource
    HttpRequestConfig requestConfig;

    @Override
    @Transactional
    public Response getPayOrderData(Map<String, String> map, HttpServletRequest request) throws Exception {
        int userNoId = 0;
        String orderNo = "";
        Order order = new Order();
        List<CartList> cartList = new ArrayList<>();
        Config config = new Config();
        PayOrder payOrder = new PayOrder();
        double cartOrderMoney = 0;
        double balanceInter = 0;
        double balanceCostInter = 0;
        double orderPayMoney = 0;
        int isHavePayPwd = 0;
        int limitCostInterInt=0;
        int groupbuyGoodsid=0;
        int groupbuyId=0;
        int participateId=0;
        if (map != null) {
            userNoId = InterfaceVer.VerNumber(map.get("userNoId"));
            orderNo = map.get("orderNo") == null ? "" : map.get("orderNo");

            payOrder.setOrderNo(orderNo);
            cartList = cartService.selectCartListByOrderNo(userNoId, orderNo);
            order = orderService.selectByOrderNo(orderNo);
            if (cartList != null && cartList.size() > 0) {
                for (CartList cartList1 : cartList) {
                    for (Carts carts : cartList1.getCartsList()) {
                        int productCount = carts.getProductCount() == null ? 0 : carts.getProductCount();
                        int limitCostInter=carts.getLimitCostInter()==null?0:carts.getLimitCostInter();
                        if(limitCostInter>0){
                            limitCostInterInt=limitCostInter;
                        }
                        double productPrice = carts.getPrice() == null ? 0 : carts.getPrice();
                        cartOrderMoney += productPrice * productCount;
                    }
                }
            }
            if (order != null) {
                if ((order.getOrderId() == null ? 0 : order.getOrderId()) > 0) {
                    groupbuyGoodsid=order.getGroupbuyGoodsid()==null?0:order.getGroupbuyGoodsid();
                    groupbuyId=order.getGroupbuyId()==null?0:order.getGroupbuyId();
                    participateId=order.getParticipateId()==null?0:order.getParticipateId();
                    int orderStatus = InterfaceVer.VerNumber(order.getOrderStatus());
                    int userNoIdOrder = order.getUsernoId() == null ? -1 : order.getUsernoId();
                    double orderMoney = order.getOrderMoney() == null ? 0 : order.getOrderMoney();
                    double orderCoupon = order.getCoupon() == null ? 0 : order.getCoupon();
                    double orderCashCoupon = order.getCashCoupon() == null ? 0 : order.getCashCoupon();
                    double freight = order.getFreight() == null ? 0 : order.getFreight();
                    //System.out.println(orderMoney+" "+orderCoupon+" "+orderCashCoupon+" "+freight);
                    orderPayMoney = orderMoney - orderCoupon - orderCashCoupon + freight;
//                    if(orderStatus!=701){
//                        return new Response(MessageConstants.MSG_SUCCESS,payOrder,0,"订单状态不正确!",request);
//                    }
//                    if(userNoId!=userNoIdOrder){
//                        return new Response(MessageConstants.MSG_SUCCESS,payOrder,0,"订单数据不正确01!",request);
//                    }
//                    if(orderMoney!=cartOrderMoney&&orderMoney!=0&&cartOrderMoney!=0){
//                        return new Response(MessageConstants.MSG_SUCCESS,payOrder,0,"订单数据不正确04!",request);
//                    }
                }
// else {
//                    return new Response(MessageConstants.MSG_SUCCESS,payOrder,0,"订单数据不正确02!",request);
//                }
                }
                JSONObject jsonObject = finaceService.getBalanceAllX(userNoId);
                if (jsonObject != null) {
                    balanceInter = InterfaceVer.VerDoubleNumber(jsonObject.get("balance1") == null ? "" : jsonObject.get("balance1").toString());
                    balanceCostInter = InterfaceVer.VerDoubleNumber(jsonObject.get("balance4") == null ? "" : jsonObject.get("balance4").toString());
                }
                try {
                    JSONObject jsonObject1 = userNoService.getUserNo(userNoId);
                    if (jsonObject1 != null) {
                        if(jsonObject1.get("paypwd")!=null){
                            isHavePayPwd = InterfaceVer.VerNumber(jsonObject1.get("paypwd").equals("")? "0" : "1");
                        }
                    }
                }catch (Exception e){}

                double a1=0,a4=0,cash=0;
                //new开始
            //1 两种积分和不够
            if((balanceCostInter+balanceInter)<orderPayMoney){
                System.out.println("k1");
                a1=balanceInter;
                a4=balanceCostInter;
                cash=orderPayMoney-(balanceCostInter+balanceInter);
            }
            //2 两种中的任意一种都够
            if(balanceCostInter>=orderPayMoney&&balanceInter>=orderPayMoney){
                System.out.println("k2");
                a1=0;
                a4=orderPayMoney;
                cash=0;
            }
            //3 消费够 积分不够
            if(balanceCostInter>=orderPayMoney&&balanceInter<orderPayMoney){
                System.out.println("k3");
//                a4=(orderPayMoney-balanceInter);
//                a1=balanceInter;
                a4=orderPayMoney;
                a1=0;
                cash=0;
            }
            //4 积分够 消费不够
            if(balanceInter>=orderPayMoney&&balanceCostInter<orderPayMoney){
                System.out.println("k4");
                a1=(orderPayMoney-balanceCostInter);
                a4=balanceCostInter;
                cash=0;
            }
            //5 两种积分和够
            if((balanceCostInter+balanceInter)>=orderPayMoney&&balanceCostInter<orderPayMoney&&balanceInter<orderPayMoney){
                System.out.println("k5");
                if(balanceCostInter>=balanceInter){
                    System.out.println("k51");
                    a4=balanceCostInter;
                    a1=(orderPayMoney-balanceCostInter);
                    cash=0;
                }
                if(balanceCostInter<balanceInter){
                    System.out.println("k52");
                    a4=(orderPayMoney-balanceInter);
                    a1=balanceInter;
                    cash=0;
                }
            }
                //new结束

//
//                if(balanceCostInter<=0&&balanceInter<=0){
//                    System.out.println("a1");
//                    a1=0;
//                    a4=0;
//                    cash=orderPayMoney-(balanceCostInter+balanceInter);
//                }
//                if(balanceCostInter<=0&&balanceInter>0){//消费积分小于等于0 积分>0
//                    System.out.println("s1");
//                    if((balanceCostInter+balanceInter)>=orderPayMoney){
//                        System.out.println("a2");
//                        a1=orderPayMoney;
//                        a4=0;
//                        cash=0;
//                        //double cash=orderPayMoney-balanceCostInter;
//                    }else {
//                        System.out.println("a3");
//                        a1=balanceInter;
//                        a4=0;
//                        cash=orderPayMoney-(balanceCostInter+balanceInter);
//                    }
//                    System.out.println("s2");
//                }
//                if(balanceInter<=0&&balanceCostInter>0){//积分小于等于0 消费积分>0
//                    System.out.println("s3");
//                    if((balanceCostInter+balanceInter)>=orderPayMoney){
//                        System.out.println("a4");
//                    a1=0;
//                    a4=orderPayMoney;
//                    cash=0;
//                    //double cash=orderPayMoney-balanceCostInter;
//                    }else {
//                        System.out.println("a5");
//                    a1=0;
//                    a4=balanceCostInter;
//                    cash=orderPayMoney-(balanceCostInter+balanceInter);
//                    }
//                    System.out.println("s4");
//            }
//                if(balanceCostInter>0&&balanceInter>0&&(balanceCostInter+balanceInter)<=orderPayMoney){
//                    System.out.println("a6");
//                    a4=balanceCostInter;
//                    a1=balanceInter;
//                    cash=orderPayMoney-balanceCostInter-balanceInter;
//                }
//            if(balanceCostInter>0&&balanceInter>0&&balanceCostInter>=orderPayMoney){
//                System.out.println("a7");
//                a4=orderPayMoney;
////                    if(limitCostInterInt>0){
////                        a1=balanceInter;
////                    }else {
////                        a1=0;
////                    }
//                a1=0;
//                cash=0;
//            }
//
//            //                if(a4!=orderPayMoney) {
//            if (balanceCostInter > 0 && balanceInter > 0 && balanceInter >= orderPayMoney) {
//                System.out.println("a8");
////                if(limitCostInterInt>0){
////                    a4=balanceCostInter;
////                }else {
////                    a4=0;
////                }
//                a4 = 0;
//                a1 = orderPayMoney;
//                cash = 0;
//            }
////                }
//
//
//            if(balanceCostInter>0&&balanceInter>0&&(balanceCostInter+balanceInter)>orderPayMoney){
//                System.out.println("balanceCostInter:"+balanceCostInter+" balanceInter:"+balanceInter+" orderPayMoney:"+orderPayMoney);
//                System.out.println("s5");
//                if(balanceCostInter>balanceInter&&balanceCostInter<orderPayMoney&&balanceInter<orderPayMoney){
//                    a4=orderPayMoney-balanceInter;
//                    a1=balanceInter;
//                    cash=0;
//                    System.out.println("a91");
//                }
//                if(balanceCostInter<balanceInter&&balanceInter<orderPayMoney&&balanceCostInter<orderPayMoney){
//                    a4=balanceCostInter;
//                    a1=orderPayMoney-balanceCostInter;
//                    cash=0;
//                    System.out.println("a92");
//                }
//                if(balanceCostInter==balanceInter&&balanceInter<orderPayMoney&&balanceCostInter<orderPayMoney){
//                    a4=balanceCostInter;
//                    a1=balanceInter;
//                    cash=0;
//                    System.out.println("a93");
//                }
//                System.out.println("s6");
//
////                double s1=orderPayMoney-balanceCostInter;
////                double s2=orderPayMoney-balanceInter;
////
////                if(s1<balanceInter){
////                    System.out.println("a91");
////                    a4=balanceCostInter;
////                    a1=s1;
////                    cash=0;
////                }
////                else if(s1>balanceInter) {
////                    System.out.println("a91");
////                    a4=balanceCostInter;
////                    a1=s1;
////                    cash=0;
////                }
////               else if(s2<balanceCostInter){
////                    System.out.println("a92");
////                    a4=balanceCostInter;
////                    a1=s2;
////                    cash=0;
////                }
//            }
            if(limitCostInterInt>0){//活动消费积分限制
                System.out.println("ss1");
                a4=0;
                if(balanceInter>orderPayMoney){
                    a1=orderPayMoney;
                }else {
                    a1=balanceInter;
                }
//                a1=balanceInter;
                cash=orderPayMoney-(a1+a4);
            }
                config = configMapper.selectByPrimaryKey(1);
                payOrder.setInterName(config.getFinacename1());
                payOrder.setCostInterName(config.getFinacename4());
                payOrder.setInter(InterfaceVer.formatDouble1(balanceInter));
                payOrder.setCostInter(InterfaceVer.formatDouble1(balanceCostInter));
                payOrder.setDeductionCostInter(InterfaceVer.formatDouble1(a4));
                payOrder.setDeductionInter(InterfaceVer.formatDouble1(a1));
                payOrder.setCash(InterfaceVer.formatDouble1(cash));
                payOrder.setOrderPayMoney(InterfaceVer.formatDouble1(orderPayMoney));
                payOrder.setIsHavePayPwd(isHavePayPwd);
                payOrder.setGroupbuyGoodsid(groupbuyGoodsid);
                payOrder.setGroupbuyId(groupbuyId);
                payOrder.setParticipateId(participateId);
                return new Response(MessageConstants.MSG_SUCCESS, payOrder, 0, "数据获取成功!", request);
            } else {
                return new Response(MessageConstants.MSG_SUCCESS, payOrder, 0, "数据获取失败!", request);
            }
        }

    @Transactional
    @Override
    public Response payInter(Map<String, String> map, HttpServletRequest request) throws Exception {
        System.out.println("------------------积分支付------------>");
        String orderNo="";
        int userNoId=0;
        double cash=0;
        double inter=0;
        double costInter=0;
        Order order=new Order();
        double orderCoupon=0;
        double orderCashCoupon=0;
        int renkIdU=0;
        if (map != null) {
            userNoId = InterfaceVer.VerNumber(map.get("userNoId"));
            orderNo=map.get("orderNo")==null?"":map.get("orderNo");
            inter = InterfaceVer.VerDoubleNumber(map.get("inter"));
            costInter = InterfaceVer.VerDoubleNumber(map.get("costInter"));
            cash = InterfaceVer.VerDoubleNumber(map.get("cash"));
            order = orderService.selectByOrderNo(orderNo);
            if(order!=null){
                double orderMoney=order.getOrderMoney()==null?0:order.getOrderMoney();
                int orderStatus= InterfaceVer.VerNumber(order.getOrderStatus());
                orderCoupon=order.getCoupon()==null?0:order.getCoupon();
                orderCashCoupon=order.getCashCoupon()==null?0:order.getCashCoupon();
                double freight=order.getFreight()==null?0:order.getFreight();
                if(request!=null){
                    if(orderStatus!=701&&orderStatus!=706){
                        return new Response(MessageConstants.MSG_PAY_ERROR,0,0,"订单状态不正确!",request);
                    }
                }
//                System.out.println("cash:"+cash);
//                System.out.println("inter:"+inter);
//                System.out.println("costInter:"+costInter);
//                System.out.println("支付:"+InterfaceVer.formatDouble1(inter+costInter+cash));
//                System.out.println("应该:"+InterfaceVer.formatDouble1(orderMoney-orderCoupon-orderCashCoupon+freight));
                if(InterfaceVer.formatDouble1(inter+costInter+cash)!= InterfaceVer.formatDouble1(orderMoney-orderCoupon-orderCashCoupon+freight)){
                    return new Response(MessageConstants.MSG_PAY_ERROR,0,0,"订单支付金额错误!",request);
                }
                Map<String,String> map1=new HashMap<>();
                map1.put("orderNo",orderNo);
                map1.put("userNoId",userNoId+"");
                map1.put("amount2",orderCoupon+"");
                map1.put("amount3",orderCashCoupon+"");
                map1.put("amount1",(inter+cash)+"");
                map1.put("amount4",costInter+"");
                JSONObject jsonObject=getPayResult(map1,request);
                if(jsonObject!=null){
                    String code = jsonObject.get("code").toString();
                    if ("000000".equals(code)) {
                        order.setInter(inter);
                        order.setCostInter(costInter);
                        order.setCash(cash);
                        order.setRealPay((inter+costInter+cash));
                        order.setOrderStatus("702");
                        order.setPayTime(new Date());
                        int res=orderService.updateByPrimaryKeySelective(order);
                        //用户等级为游客 提升用户等级
                        JSONObject jsonObjectUserNo=userNoService.getUserNo(userNoId);
                        if(jsonObjectUserNo!=null){
                            int rankId = InterfaceVer.VerNumber(jsonObjectUserNo.get("rankId") == null ? "" : jsonObjectUserNo.get("rankId").toString());
                            if(rankId==1){//当前用户是游客的话 提升为会员
                                renkIdU=2;
                            }
                        }else {
                            System.out.println("-----------------------------------------用户信息有误-------------------->");
                            return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"用户信息有误!",request);
                        }
                        //
                        if(res>0) {
                            try {
                                List<CartList> lists=cartService.selectCartListByOrderNo(userNoId,orderNo);
                                if(lists!=null&&lists.size()>0){
                                    for (CartList cartList:lists) {
                                        if(cartList.getCartsList()!=null&&cartList.getCartsList().size()>0){
                                            for (Carts carts:cartList.getCartsList()) {
                                                int zoneId=carts.getZoneId()==null?0:carts.getZoneId();
                                                if(zoneId==17){
                                                    renkIdU=3;//17开店产品提升会员等级为一星店主
                                                }
                                            }
                                        }
                                    }
                                }
                                JSONObject jsonObject1=userNoService.updateRankId(userNoId,renkIdU);

                            }catch (Exception e){}

                            //团购处理
                            try {
                                System.out.println("----------------------------支付成功团购----------------------->"+order.getParticipateId());
                                int groupbuyId=order.getGroupbuyId()==null?0:order.getGroupbuyId();
                                int participateId=order.getParticipateId()==null?0:order.getParticipateId();
                              Map<String,Object> mapGroupBuy=groupbuyService.updateGroupbuyStatus(groupbuyId,participateId);
                            }catch (Exception ee){}
                            //团购处理

                            return new Response(MessageConstants.MSG_SUCCESS, 1, 1, "支付成功!", request);
                        }else {
                            throw new RuntimeException();
                        }
                    }else {
                        String errorDetail = jsonObject.get("errorDetail").toString();
                        order.setInter(inter);
                        order.setCostInter(costInter);
                        order.setCash(cash);
                        order.setRealPay((inter+costInter+cash));
                        order.setPayErrorInfo(errorDetail+"A");
                        int res=orderService.updateByPrimaryKeySelective(order);
                        return new Response(MessageConstants.MSG_PAY_ERROR,0,0,errorDetail+"A",request);
                    }
                }else {
                    String errorDetail = "积分支付接口error：finace";
                    order.setInter(inter);
                    order.setCostInter(costInter);
                    order.setCash(cash);
                    order.setRealPay((inter+costInter+cash));
                    order.setPayErrorInfo(errorDetail+"B");
                    int res=orderService.updateByPrimaryKeySelective(order);
                    return new Response(MessageConstants.MSG_PAY_ERROR,0,0,"支付失败!",request);
                }
            }else {
                return new Response(MessageConstants.MSG_PAY_ERROR,0,0,"订单数据不正确!",request);
            }
        }else {
            return new Response(MessageConstants.MSG_PAY_ERROR,0,0,"参数有误!",request);
        }
    }


//    @Override
//    public Response pay(Map<String, String> map, HttpServletRequest request) throws Exception {
////        int userNoId = OrderVer.VerNumber(map.get("userNoId"));
////        String orderNo=map.get("orderNo")==null?"":map.get("orderNo");
////        double inter = OrderVer.VerDoubleNumber(map.get("inter"));
////        double costInter = OrderVer.VerDoubleNumber(map.get("costInter"));
////        double coupon=OrderVer.VerDoubleNumber(map.get("coupon"));
////        double cashCoupon=OrderVer.VerDoubleNumber(map.get("cashCoupon"));
//        JSONObject resultData=getPayResult(map,request);
//        if(resultData!=null){
//            return new Response(MessageConstants.MSG_SUCCESS,0,0,"订单数据不正确!",request);
//        }else {
//return null;
//        }
//    }

    @Override
    public JSONObject getPayResult(Map<String, String> map, HttpServletRequest request) throws Exception {
        try {
            int userNoId1 = InterfaceVer.VerNumber(map.get("userNoId"));
            String orderNo=map.get("orderNo")==null?"":map.get("orderNo");
            double inter = InterfaceVer.VerDoubleNumber(map.get("amount1"));
            double costInter = InterfaceVer.VerDoubleNumber(map.get("amount4"));
            double coupon= InterfaceVer.VerDoubleNumber(map.get("amount2"));
            double cashCoupon= InterfaceVer.VerDoubleNumber(map.get("amount3"));
            String url = HttpRequestConfig.finaceServerUrl+"/wap/SetFinaceOrder";
            //String url = "http://192.168.0.176:8087/wap/SetFinaceOrder";
            String sentStr = "userNoId=" + userNoId1;
            sentStr +="&orderNo="+orderNo;
            sentStr +="&amount1="+inter;
            sentStr +="&amount2="+coupon;
            sentStr +="&amount3="+cashCoupon;
            sentStr +="&amount4="+costInter;
            System.out.println(sentStr);
            String result = HttpRequest.sendPost(url, sentStr);
            JSONObject str = JSONObject.parseObject(result);
            return str;
        }catch (Exception e){
            String str="{ \"msg\": \"\", \"code\": \"2\", \"data\":null, \"count\": 1, \"errorDetail\": "+e.getMessage()+" }";
            JSONObject strs = JSONObject.parseObject(str);
            return strs;
        }

//        String code = str.get("code").toString();
//        if ("000000".equals(code)) {
////            JSONObject strData = JSONObject.parseObject(str.get("data").toString());
////            return strData;
//            return str;
//        } else {
//            return null;
//        }
    }


}
